<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="top-panel">
      <view class="header">
        <u-icon name="arrow-left" size="40" color="#333" @click="goBack" class="back-button"></u-icon>
        <text class="title">体检订单</text>
      </view>
    </view>

    <!-- 订单列表 -->
    <view class="order-list">
      <view class="order-item" v-for="(order, index) in orderList" :key="index">
        <view class="order-info">
          <text class="order-title">订单号: {{ order.outTradeNo.substring(0, 5) }}</text>
          <view class="order-detail">
            <text class="detail-label">医院: </text>
            <text class="detail-value">{{ order.hospitalName || '加载中...' }}</text>
          </view>
          <view class="order-detail">
            <text class="detail-label">就诊人: </text>
            <text class="detail-value">{{ order.patientName || '加载中...' }}</text>
          </view>
          <view class="order-detail">
            <text class="detail-label">套餐: </text>
            <text class="detail-value">{{ order.packageName || '加载中...' }}</text>
          </view>
          <view class="order-detail">
            <text class="detail-label">金额: </text>
            <text class="detail-value">¥{{ order.totalAmount }}</text>
          </view>
          <view class="order-detail">
            <text class="detail-label">状态: </text>
            <text class="detail-value" :style="{ color: getStatusColor(order.status) }">{{ order.status }}</text>
          </view>
        </view>
        <view class="action-button" :class="{ 'disabled': order.status !== '待支付' }" @click="handlePayment(order)">
          <text>去支付</text>
        </view>
      </view>
      <view v-if="orderList.length === 0" class="empty-message">
        <text>暂无订单</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderList: [], // 订单列表
      userId: null,  // 用户ID
      isLoading: false, // 加载状态
    };
  },
  onLoad() {
    let userInfo = uni.getStorageSync('userInfo');
    if (userInfo && userInfo.id) {
      this.userId = userInfo.id;
    } else {
      console.warn('未找到用户ID，跳转到登录页面');
      this.userId = '1'; // 兜底值，仅用于测试
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000,
        success: () => {
          setTimeout(() => {
            uni.navigateTo({ url: '/pages/public/login' });
          }, 2000);
        }
      });
    }
    this.fetchOrderList();
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    // 查询订单列表
    fetchOrderList() {
      if (!this.userId) {
        uni.showToast({
          title: '用户ID无效，请重新登录',
          icon: 'none'
        });
        return;
      }
      this.isLoading = true;
      uni.request({
        url: `http://localhost:8080/app/physical/order/list/${this.userId}`,
        method: 'GET',
        success: (res) => {
          if (res.data.code === 200) {
            this.orderList = res.data.data || [];
            // 并行加载详情
            this.loadOrderDetails();
          } else {
            uni.showToast({
              title: res.data.msg || '查询订单列表失败',
              icon: 'none'
            });
            this.orderList = [];
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'none'
          });
          this.orderList = [];
        },
        complete: () => {
          this.isLoading = false;
        }
      });
    },
    // 并行加载订单详情
    loadOrderDetails() {
      const requests = this.orderList.map(order => {
        return Promise.all([
          this.fetchHospitalDetail(order),
          this.fetchPatientDetail(order),
          this.fetchPackageDetail(order)
        ]);
      });
      Promise.all(requests).then(() => {
        this.$forceUpdate(); // 确保视图更新
      }).catch(err => {
        console.error('加载详情失败:', err);
      });
    },
    // 查询医院详情
    fetchHospitalDetail(order) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `http://localhost:8080/app/hospital/detail/${order.hospitalId}`,
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200) {
              order.hospitalName = res.data.data.name;
            } else {
              order.hospitalName = '未知医院';
            }
            resolve();
          },
          fail: (err) => {
            order.hospitalName = '未知医院';
            reject(err);
          }
        });
      });
    },
    // 查询就诊人详情
    fetchPatientDetail(order) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: 'http://localhost:8080/app/hospital/patient/list',
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200) {
              const patient = res.data.rows.find(item => item.id === order.patientId);
              order.patientName = patient ? patient.name : '未知就诊人';
            } else {
              order.patientName = '未知就诊人';
            }
            resolve();
          },
          fail: (err) => {
            order.patientName = '未知就诊人';
            reject(err);
          }
        });
      });
    },
    // 查询套餐详情
    fetchPackageDetail(order) {
      return new Promise((resolve, reject) => {
        uni.request({
          url: `http://localhost:8080/app/physical/order/detail/${order.packageId}`, // 修正接口路径
          method: 'GET',
          success: (res) => {
            if (res.data.code === 200) {
              order.packageName = res.data.data.packageName || '未知套餐';
            } else {
              order.packageName = '未知套餐';
            }
            resolve();
          },
          fail: (err) => {
            order.packageName = '未知套餐';
            reject(err);
          }
        });
      });
    },
    // 根据状态返回颜色
    getStatusColor(status) {
      switch (status) {
        case '待支付':
          return '#FF4444';
        case '已支付':
          return '#00AA00';
        case '已取消':
          return '#999999';
        default:
          return '#333333';
      }
    },
    // 处理支付按钮点击
    handlePayment(order) {
      if (order.status !== '待支付') {
        return;
      }
      uni.navigateTo({
        url: `/pages/physical/continuePay?outTradeNo=${order.outTradeNo}&totalAmount=${order.totalAmount}&status=${order.status}&packageId=${order.packageId}&hospitalId=${order.hospitalId}&patientId=${order.patientId}&appointmentTime=${order.appointmentTime || new Date().toISOString().split('T')[0]}&packageName=${encodeURIComponent(order.packageName || '')}&hospitalName=${encodeURIComponent(order.hospitalName || '')}&patientName=${encodeURIComponent(order.patientName || '')}`
      });
    }
  }
};
</script>

<style>
.container {
  padding: 20rpx;
  height: 100vh;
  overflow: auto;
}

.top-panel {
  background-color: #fff;
  padding: 10rpx 20rpx;
  border-bottom: 1rpx solid #eee;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.back-button {
  position: absolute;
  left: 10rpx;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.order-list {
  margin-top: 20rpx;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
  background-color: #fff;
  position: relative;
}

.order-info {
  flex: 1;
}

.order-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
}

.order-detail {
  margin-top: 10rpx;
  display: flex;
  align-items: center;
}

.detail-label {
  font-size: 26rpx;
  color: #666;
  width: 120rpx;
}

.detail-value {
  font-size: 26rpx;
  color: #333;
}

.action-button {
  width: 120rpx;
  height: 50rpx;
  background-color: #007AFF;
  border-radius: 25rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  right: 20rpx;
}

.action-button.disabled {
  background-color: #cccccc;
  pointer-events: none;
}

.action-button text {
  color: #fff;
  font-size: 24rpx;
}

.empty-message {
  text-align: center;
  padding: 40rpx;
  color: #666;
  font-size: 28rpx;
}
</style>